package cn.bdqn.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class MyZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 要验证有没有权限，需要看请求中有没有带令牌(request headers)
        // 需要获取请求对象 request
        RequestContext ctx = RequestContext.getCurrentContext();
        // 取出当前的请求对象
        HttpServletRequest request = ctx.getRequest();
        // 获取请求中的令牌
        Object accessToken = request.getParameter("token");
        // 判断有没有带令牌
        if(accessToken == null) {
            // 没带令牌，说明没有权限
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        return null;
    }
}
